package com.xindaoapp.happypet.ui;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.HomeBannerDetailActivity;
import com.xindaoapp.happypet.activity.MyClubActivity;
import com.xindaoapp.happypet.adapter.CommunityAdapter;
import com.xindaoapp.happypet.adapter.HZTAdapter;
import com.xindaoapp.happypet.adapter.MyPostListAdapter2;
import com.xindaoapp.happypet.adapter.MyPostListAdapter2.OnNextPageListener;
import com.xindaoapp.happypet.adapter.XinDaoBaseAdapter.ILoadNextPageData;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.Groups;
import com.xindaoapp.happypet.bean.Groups.Group;
import com.xindaoapp.happypet.bean.HomeBanner;
import com.xindaoapp.happypet.bean.HomeBannerEntity;
import com.xindaoapp.happypet.bean.Message;
import com.xindaoapp.happypet.bean.PostListEntity;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.xdConfig;
import com.xindaoapp.happypet.view.CircleImageView;
import com.xindaoapp.happypet.view.HZTLayout;
import com.xindaoapp.happypet.view.MyGridView;
import com.xindaoapp.happypet.view.RollViewPager;

/**
 * 圈子(1.4版本，首页第二个tab页)
 * 
 * @author Yomine
 */
public class CommunityFragment extends BaseFragment implements OnClickListener {

    public CommunityFragment() {
        super();
        // TODO Auto-generated constructor stub
    }

    private TextView mTitle;
    private ImageView mBackView;
    private PullToRefreshListView mRefreshListView;
    private View rootView;
    /** 推荐圈子 */
    // private MyGridView mGridGroom;
    private List<Group> groomGroups;
    /** 我的圈子 */
    private MyGridView mGridMine;
    private List<Group> mineGroups;
    /** 轮播图 */
    private LinearLayout mViewPager;
    private TextView mtvDescription;
    private LinearLayout mllPoints;

    private List<HomeBanner> mBanners;

    private boolean mFrist = true;

    private Adapter groomAdapter;
    private MineAdapter mineAdapter;

    private final String MINEGROUPS = "minegroups";

    private JoinOutReciver joinOutReciver;
    private final CommunityAdapter postListAdapter = null;// 动态圈子列表
    private List<Message> postList = new ArrayList<Message>();
    private final List<Group> recommendarray = new ArrayList<Group>();
    private int pageNums = 1;
    private int postListCount = 0;

    private boolean isPullDown2Refresh = false;// 是否为下拉刷新

    private LoginSuccessReceiver loginSuccessReceiver;

    private TextView vDabang, vDaren, vNiuniu;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return mView = inflater.inflate(R.layout.fragment_community, container, false);
    }

    @Override
    protected void initViews() {

        mRefreshListView = (PullToRefreshListView) mView.findViewById(R.id.scrollView);

        rootView = mInflater.inflate(R.layout.scroll_community, null);
        movieLayout = (HZTLayout) rootView.findViewById(R.id.movieLayout);

        // mGridGroom = (MyGridView) rootView.findViewById(R.id.groom);
        mGridMine = (MyGridView) rootView.findViewById(R.id.mine);
        mViewPager = (LinearLayout) rootView.findViewById(R.id.viewpager1);
        mViewPager.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                CommonParameter.sScreenWidth * 248 / 640));
        mtvDescription = (TextView) rootView.findViewById(R.id.tv_image_description1);
        mllPoints = (LinearLayout) rootView.findViewById(R.id.ll_points1);
        if (mRefreshListView.getRefreshableView().getHeaderViewsCount() <= 1) {
            mRefreshListView.getRefreshableView().addHeaderView(rootView);
        }

        vDaren = (TextView) rootView.findViewById(R.id.daren);
        vDabang = (TextView) rootView.findViewById(R.id.dabang);
        vNiuniu = (TextView) rootView.findViewById(R.id.niuniu);

        mRefreshListView.getRefreshableView().setAdapter(null);


        mBackToTop = mView.findViewById(R.id.back_top);
        mBackToTop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mRefreshListView.getRefreshableView().setSelection(0);
            }
        });

        mRefreshListView.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                if (firstVisibleItem >= 10) {
                    mBackToTop.setVisibility(View.VISIBLE);
                } else {
                    mBackToTop.setVisibility(View.GONE);
                }
            }
        });
        super.initViews();
    }

    @Override
    protected void initEvents() {
        loginSuccessReceiver = new LoginSuccessReceiver();
        mContext.registerReceiver(loginSuccessReceiver, new IntentFilter(
                Constants.ACTION_LOGIN_STATE_CHANGED));

        adapter = new HZTAdapter(mContext);

        mineGroups = new LinkedList<Group>();
        joinOutReciver = new JoinOutReciver();
        mContext.registerReceiver(joinOutReciver, new IntentFilter(Constants.JOIN_OUT_GROUP));

        mRefreshListView.setMode(Mode.PULL_FROM_START);
        mRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                isPullDown2Refresh = true;
                getBannerData();
                getMineGroups();
                pageNums = 1;
                postList.clear();
                getDongtaiListView();
            }
        });

        mRefreshListView.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Message post = (Message) parent.getAdapter().getItem(position);
                if (post != null && !TextUtils.isEmpty(post.tid)) {
                    Intent intent = new Intent(mContext, PostDetailActivity.class);
                    intent.putExtra(Constants.KEY_FROM_PAGE, 0);
                    intent.putExtra(Constants.KEY_POST_TID, post.tid);
                    intent.putExtra(Constants.KEY_FROM_PAGE, 1);
                    mContext.startActivity(intent);
                }
            }
        });
        super.initEvents();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unregisterReceiver(loginSuccessReceiver);
        getActivity().unregisterReceiver(joinOutReciver);
    }

    @Override
    protected void loadDatas() {
        getBannerData();
        getMineGroups();
        getDongtaiListView();
        super.loadDatas();
    }

    /**
     * 获取动态圈子列表
     */
    private void getDongtaiListView() {
        RequestParams params = new RequestParams();
        params.put("page", String.valueOf(pageNums));
        params.put("pagesize", xdConfig.PAGE_SIZE + "");
        getMoccaApi().getDongtaiList(params, new IRequest<PostListEntity>() {
            @Override
            public void request(PostListEntity entity) {
                if (entity == null) {
                    return;
                }
                if (!TextUtils.isEmpty(entity.total)) {
                    try {
                        postListCount = Integer.parseInt(entity.total);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
                if (entity.array != null && entity.array.size() > 0) {
                    // if (isPullDown2Refresh)
                    // postListAdapter.clearData(postList);
                    postList = entity.array;
                    List<Message> message = new ArrayList<Message>();
                    message.addAll(entity.array);
                    MyPostListAdapter2 mAdapter1 =
                            new MyPostListAdapter2(mContext, message, Constants.PAGE_SIZE,
                                    R.layout.activity_community_item, R.layout.item_loading);
                    mAdapter1.setOnNextPageListener(onNextPageListener);
                    mAdapter1.setShowCommunity(true);
                    mRefreshListView.getRefreshableView().setAdapter(mAdapter1);
                }
                mRefreshListView.onRefreshComplete();

                setLastUpdateTime();
            }
        });
    }


    /**
     * 加載下一頁的方法
     */
    private final OnNextPageListener onNextPageListener = new OnNextPageListener() {

        @Override
        public void nextPage(int start, int size, final ILoadNextPageData<Message> iLoadNextPageData) {
            RequestParams params = new RequestParams();
            params.put("page", String.valueOf(start));
            params.put("pagesize", String.valueOf(size));
            getMoccaApi().getDongtaiList(params, new IRequest<PostListEntity>() {
                @Override
                public void request(PostListEntity entity) {
                    if (entity == null) {
                        return;
                    }
                    if (entity.array != null && entity.array.size() > 0) {
                        List<Message> message = new ArrayList<Message>();
                        message.addAll(entity.array);
                        iLoadNextPageData.loadNextPageData(message);
                    }
                }
            });
        }
    };

    /**
     * 设置最后刷新时间
     */
    private void setLastUpdateTime() {
        String text = CommonUtil.formatPullToRefreshDate();
        mRefreshListView.setLastUpdatedLabel(text);
    }

    private void getMineGroups() {
        getMoccaApi().getMineGroups(new IRequest<Groups>() {
            @Override
            public void request(Groups t) {
                if (null == t) {
                    getMineGroupsLocal(null);
                } else {
                    if (t.getResult().equals(mResult)) {
                        // recommendarray.clear();
                        List<Group> array = t.array;
                        // recommendarray = t.recommendarray;
                        if (null != array && array.size() > 0) {
                            getMineGroupsLocal(array);
                        } else {
                            getMineGroupsLocal(null);
                        }
                        // if (recommendarray != null && recommendarray.size() > 0) {
                        // getRecommentGroups(recommendarray);
                        // } else {
                        // getRecommentGroups(null);
                        // }
                    } else {
                        // getRecommentGroups(null);
                        getMineGroupsLocal(null);
                        if (!TextUtils.isEmpty(t.getMsg())) {
                            Toast.makeText(mContext, t.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }


        });
    }

    /**
     * @param recommendarray 推荐圈子
     */
    private void getRecommentGroups(List<Group> recommendarray) {
        adapter.clearObject();
        adapter.addObject(recommendarray);
        adapter.notifyDataSetChanged();
        movieLayout.setAdapter(adapter);
    }

    /** 获取我的圈子 */
    private void getMineGroupsLocal(List<Group> localGroups) {
        if (null != localGroups && localGroups.size() > 0) {
            mineGroups.clear();
            mineGroups.addAll(localGroups);
        } else {
            if (mineGroups.size() > 0) {
                mineGroups.clear();
                // mineGroups.remove(mineGroups.size() - 1);
            }
        }
        mineGroups.add(new Group("1000000", "添加", "333", "4444"));
        mineAdapter = new MineAdapter(mineGroups);
        mGridMine.setAdapter(mineAdapter);
        mineAdapter.notifyDataSetChanged();
        mGridMine.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mineAdapter.getItems().size() >= 1) {
                    if (position == mineAdapter.getItems().size() - 1) {
                        Intent intent = new Intent(mContext, AddGroupActivity.class);
                        startActivity(intent);
                    } else {
                        if (mineAdapter.getItems().size() > 1) {
                            Intent intent = new Intent(mContext, MyClubActivity.class);
                            intent.putExtra("name", mineGroups.get(position).name);
                            intent.putExtra("fId", mineGroups.get(position).fid);
                            Constants.ISMYGROUP = true;
                            startActivity(intent);
                        }
                    }
                }
            }
        });
    }



    private void getBannerData() {
        if (CommonUtil.checkNetState(mContext)) {
            getMoccaApi().getIndexBanner("group", new IRequest<HomeBannerEntity>() {
                @Override
                public void request(HomeBannerEntity t) {
                    mRefreshListView.onRefreshComplete();
                    if (null == t) {
                        if (mFrist) {
                            onDataArrived(false);
                            load_fail.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    startAnimation();
                                    loadDatas();
                                }
                            });
                        }
                    } else {
                        if (mBanners != null && mBanners.size() > 0) {
                            mBanners.clear();
                        }
                        initEventsByLoadData();
                        mFrist = false;
                        onDataArrived(true);
                        if (t.getResult().equals(mResult) && t.getArray().size() > 0) {
                            mBanners = t.getArray();
                            prepareViewPage(mContext, mBanners);
                        }
                    }
                }
            });
        } else {

            HappyPetApplication.mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub

                    mRefreshListView.onRefreshComplete();
                }
            }, 300);

            if (mFrist) {
                onDataArrived(false);
                load_fail.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startAnimation();
                        loadDatas();
                    }
                });
            }
            Toast.makeText(mContext, R.string.pLease_check_network, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 加载数据完成后，初始化点击事件
     */
    protected void initEventsByLoadData() {
        vDabang.setOnClickListener(this);
        vDaren.setOnClickListener(this);
        vNiuniu.setOnClickListener(this);
    }

    private ArrayList<View> dotLists;
    private RollViewPager rollViewPager;
    private HZTLayout movieLayout;// 横向滚动推荐列表
    private HZTAdapter adapter;
    private View mBackToTop;

    public void prepareViewPage(final Context context, final List<HomeBanner> list) {
        List<String> titleList = new ArrayList<String>();
        List<String> imageUrlList = new ArrayList<String>();
        for (HomeBanner homeBanner : list) {
            titleList.add(homeBanner.getTitle());
            imageUrlList.add(homeBanner.getCoverpath());
        }
        initDots(list.size());
        rollViewPager =
                new RollViewPager(context, dotLists, R.drawable.point_normal,
                        R.drawable.point_enable, new RollViewPager.MyOnTouchCllickCallBack() {
                            @Override
                            public void OnTouchCllick(int position) {
                                String type = list.get(position % list.size()).getType();
                                if (type.equals("web")) {// 跳转到详情
                                    Intent intent1 =
                                            new Intent(context, HomeBannerDetailActivity.class);
                                    intent1.putExtra("url", list.get(position % list.size())
                                            .getLink());
                                    context.startActivity(intent1);
                                    getActivity().overridePendingTransition(
                                            R.anim.new_dync_in_from_right,
                                            R.anim.new_dync_out_to_left);
                                } else if (type.equals("appthread")) {// 跳转到帖子详情
                                    Intent intent2 = new Intent(context, PostDetailActivity.class);
                                    intent2.putExtra(Constants.KEY_POST_TID,
                                            list.get(position % list.size()).getLink());
                                    context.startActivity(intent2);
                                    getActivity().overridePendingTransition(
                                            R.anim.new_dync_in_from_right,
                                            R.anim.new_dync_out_to_left);
                                }
                            }
                        });
        rollViewPager.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                CommonParameter.sScreenWidth * 248 / 640));
        rollViewPager.setTitle(mtvDescription, titleList);
        rollViewPager.setImageUrl(imageUrlList);
        rollViewPager.startRoll();
        mViewPager.removeAllViews();
        mViewPager.addView(rollViewPager);
    }

    private void initDots(int size) {
        dotLists = new ArrayList<View>();
        mllPoints.removeAllViews();
        for (int i = 0; i < size; i++) {
            LinearLayout.LayoutParams layoutParams =
                    new LinearLayout.LayoutParams(CommonUtil.dip2px(mContext, 5),
                            CommonUtil.dip2px(mContext, 5));
            layoutParams.setMargins(5, 0, 5, 8);
            // LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(15,
            // 15);

            // lp.leftMargin = 10;

            ImageView m = new ImageView(mContext);
            // m.setLayoutParams(new LayoutParams(CommonUtil.dip2px(mContext, 3), CommonUtil.dip2px(
            // mContext, 3)));
            if (i == 0) {
                m.setBackgroundResource(R.drawable.point_enable);
            } else {
                m.setBackgroundResource(R.drawable.point_normal);
            }
            m.setLayoutParams(layoutParams);
            dotLists.add(m);
            mllPoints.addView(m);
        }
    }

    private class Adapter extends BaseAdapter {
        private final List<Group> groups;

        public Adapter(List<Group> groups) {
            super();
            this.groups = groups;
        }

        @Override
        public int getCount() {
            return groups.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(mContext, R.layout.left_nemu_list, null);
                holder.iv_item_list = (CircleImageView) convertView.findViewById(R.id.iv_item_list);
                holder.tv_item_list = (TextView) convertView.findViewById(R.id.tv_item_list);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            ImageLoader.getInstance().displayImage(groups.get(position).ico, holder.iv_item_list);
            holder.tv_item_list.setText(groups.get(position).name);
            holder.tv_item_list.setTextColor(android.graphics.Color.BLACK);
            return convertView;
        }
    }

    private class ViewHolder {
        CircleImageView iv_item_list;
        TextView tv_item_list;
    }
    /** 我加入的圈子 */
    private class MineAdapter extends BaseAdapter {
        private final List<Group> groups;

        public MineAdapter(List<Group> groups) {
            super();
            this.groups = groups;
        }

        @Override
        public int getCount() {
            return groups.size();
        }

        public List<Group> getItems() {
            if (null != groups) {
                return groups;
            }
            return null;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(mContext, R.layout.left_nemu_list, null);
                holder.iv_item_list = (CircleImageView) convertView.findViewById(R.id.iv_item_list);
                holder.tv_item_list = (TextView) convertView.findViewById(R.id.tv_item_list);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (position == groups.size() - 1) {
                holder.iv_item_list.setImageResource(R.drawable.left_menu_add);
                holder.tv_item_list.setText(groups.get(position).name);
            } else {
                if (groups.size() > 1) {
                    try {
                        ImageLoader.getInstance().displayImage(groups.get(position).ico,
                                holder.iv_item_list);
                        try {
                            holder.tv_item_list.setText(groups.get(position).name
                                    .replace("俱乐部", ""));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            try {
                holder.tv_item_list.setText(groups.get(position).name.replace("俱乐部", ""));
            } catch (Exception e) {
                e.printStackTrace();
            }
            holder.tv_item_list.setTextColor(getResources().getColor(R.color.info_common));
            return convertView;
        }
    }
    private class JoinOutReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // getMineGroups();
        }
    }

    private class LoginSuccessReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // loadDatas();
        }
    }

    @Override
    public void onDestroy() {
        // if (null != joinOutReciver) {
        // mContext.unregisterReceiver(joinOutReciver);
        // }
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.niuniu:
                if (UserState.isLogged(getActivity())) {
                    Intent intent = new Intent(mContext, ChangeCenterActivity.class);
                    mContext.startActivity(intent);
                }
                break;
            case R.id.daren:
                Intent dayen = new Intent(mContext, DayenActivity.class);
                mContext.startActivity(dayen);
                break;
            case R.id.dabang:
                Intent list = new Intent(mContext, ListActivity.class);
                mContext.startActivity(list);
                break;

            default:
                break;
        }
    }
}
